package pro.shushi.pamirs.demo.core.manager;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import pro.shushi.pamirs.message.conf.SmsAliyunConfig;
import pro.shushi.pamirs.message.engine.MessageEngine;
import pro.shushi.pamirs.message.engine.email.EmailSender;
import pro.shushi.pamirs.message.engine.sms.SMSSender;
import pro.shushi.pamirs.message.enmu.*;
import pro.shushi.pamirs.message.model.EmailSenderSource;
import pro.shushi.pamirs.message.model.EmailTemplate;
import pro.shushi.pamirs.message.model.SmsChannelConfig;
import pro.shushi.pamirs.message.model.SmsTemplate;
import pro.shushi.pamirs.meta.annotation.fun.extern.Slf4j;
import pro.shushi.pamirs.meta.common.exception.PamirsException;
import pro.shushi.pamirs.meta.util.JsonUtils;
import pro.shushi.pamirs.user.api.model.PamirsUser;
import pro.shushi.pamirs.workflow.app.api.definition.node.NodeField;
import pro.shushi.pamirs.workflow.app.api.definition.node.NodePerson;
import pro.shushi.pamirs.workflow.app.api.definition.node.ShortMessageNode;
import pro.shushi.pamirs.workflow.app.api.pmodel.WorkflowSmsTemplate4Node;
import pro.shushi.pamirs.workflow.app.api.utils.WorkflowExp;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 示例代码-消息
 * @author haibo(xf.z @ shushi.pro)
 * @date 2023/7/8 14:16
 */
@Component
@Slf4j
public class SendMessageManager {

    /**
     * 代码中使用消息组件发送Email
     */
    public void sendEmailByTemplate(){
        try {
            EmailSender emailSender = (EmailSender) MessageEngine.get(MessageEngineTypeEnum.EMAIL_SEND).get(null);;
            EmailTemplate template = new EmailTemplate().setName("邮件模版名称").queryOne();
            //标题：${name}
            //内容：${fieldInt}次数
            String sendTo = "xxx@xxx.com";
            String copyTo = "yyy@yyy.com";

            Map<String, Object> objectData = new HashMap<>();
            objectData.put("name","张三");
            objectData.put("fieldInt",999);
            Boolean aBoolean = emailSender.send(template, objectData, sendTo, copyTo);
            if (null == aBoolean || !aBoolean) {
                log.error("发送邮件失败");
            }
        } catch (Exception e) {
            log.error("发送确认邮件失败:,异常:{}", e);
        }
    }

    /**
     * 初始化邮件模板
     */
    private void initEmailTemplate(){
        EmailSenderSource emailSenderSource = new EmailSenderSource();
        emailSenderSource.setName("邮件发送服务");
        emailSenderSource.setType(MessageEngineTypeEnum.EMAIL_SEND);
        //优先级
        emailSenderSource.setSequence(10);
        //发送账号
        emailSenderSource.setSmtpUser("xxx@xxx.com");
        //发送密码
        emailSenderSource.setSmtpPassword("xxxxxx");
        //发送服务器地址和端口
        emailSenderSource.setSmtpHost("smtp.exmail.qq.com");
        emailSenderSource.setSmtpPort(465);
        //" None: SMTP 对话用明文完成。" +
        //" TLS (STARTTLS): SMTP对话的开始时要求TLS 加密 (建议)" +
        //" SSL/TLS: SMTP对话通过专用端口用 SSL/TLS 加密 (默认是: 465)")
        emailSenderSource.setSmtpSecurity(EmailSendSecurityEnum.SSL);
        emailSenderSource.setActive(true);
        emailSenderSource.createOrUpdate();

        List<EmailTemplate> templates = new ArrayList<>();
        templates.add(new EmailTemplate().setName("重置密码邮件模板").setTitle("请确认你的密码修改请求").setBody("<p>Hi ${realname}，</p><p>请确认你的密码修改请求。如果不是你的密码修改请求，请忽略该邮件。</p><p><a href=\\\"www.oinone.top\\\" target=\\\"_blank\\\">点击链接确认</a>。</p><p>最好的祝愿，</p><p>Oinone</p>").setModel(PamirsUser.MODEL_MODEL).setEmailSenderSource(emailSenderSource));
        templates.add(new EmailTemplate().setName("修改邮箱邮件模板").setTitle("请确认你的邮箱修改请求").setBody("<p>Hi ${realname}，</p><p>请确认你的邮箱修改请求。如果不是你的邮箱修改请求，请忽略该邮件。</p><p><a href=\\\"www.oinone.top\\\" target=\\\"_blank\\\">点击链接确认</a>。</p><p>最好的祝愿，</p><p>Oinone</p>").setModel(PamirsUser.MODEL_MODEL).setEmailSenderSource(emailSenderSource));
        templates.add(new EmailTemplate().setName("确认修改邮箱邮件模板").setTitle("请确认你的新邮箱").setBody("<p>Hi ${realname}，</p><p>请确认你的新邮箱：cc@shushi.pro。</p><p>如果不是你的新邮箱修改请求，请忽略该邮件。</p><p><a href=\\\"www.oinone.top\\\" target=\\\"_blank\\\">点击链接确认</a>。</p><p>最好的祝愿，</p><p>Oinone</p>").setModel(PamirsUser.MODEL_MODEL).setEmailSenderSource(emailSenderSource));
        new EmailTemplate().createOrUpdateBatch(templates);
    }

    private void initSmsConfig() {
        SmsChannelConfig smsChannelConfig = new SmsChannelConfig()
                .setChannel(SMSChannelEnum.ALIYUN)
                .setAccessKeyId("xxxxxxxx")
                .setSignName("xxxx")
                .queryOne();
        if (null == smsChannelConfig) {
            smsChannelConfig.setChannel(SMSChannelEnum.ALIYUN);
            smsChannelConfig.setType(MessageEngineTypeEnum.SMS_SEND);
            smsChannelConfig.setSignatureMethod("HMAC-SHA1");
            smsChannelConfig.setEndpoint("https://dysmsapi.aliyuncs.com");
            smsChannelConfig.setVersion("2017-05-25");
            smsChannelConfig.setAccessKeyId("xxxxxxxxxxxxx");
            smsChannelConfig.setAccessKeySecret("xxxxxxxxxxxx");
            smsChannelConfig.setSignatureVersion("1.0");
            smsChannelConfig.setRegionId("cn-hangzhou");
            smsChannelConfig.setTimeZone("GMT");
            smsChannelConfig.setSignName("xxxxxx");
            smsChannelConfig.setActive(Boolean.TRUE);
            smsChannelConfig.create();
        } else {
            smsChannelConfig.updateById();
        }

        //初始化短信模版，需要先到阿里云申请短信模版
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setChannel(SMSChannelEnum.ALIYUN);
        smsTemplate.setTemplateType(SMSTemplateTypeEnum.SIGN_IN);
        smsTemplate.setTemplateCode("SMS_252710149");//阿里云短信模版的Code
        smsTemplate.setTemplateContent("验证码: ${code}，您正在登录。10分钟内有效，请注意保密，请勿向他人泄露您的验证码。");//阿里云短信模版

        List<SmsTemplate> smsTemplates = new ArrayList<>();
        smsTemplates.add(smsTemplate);
        new SmsTemplate().createOrUpdateBatch(smsTemplates);
    }

    public void sendSms(){
        try {

            List<String> receivePhoneNumbers = new ArrayList<>();
            receivePhoneNumbers.add("13800000000");
            // 占位符处理
            Map<String, String> vars = new HashMap<>();
            vars.put("code", "123456");

            SmsTemplate smsTemplate = new SmsTemplate().setChannel(SMSChannelEnum.ALIYUN);
            smsTemplate.setTemplateType(SMSTemplateTypeEnum.SIGN_IN);
            smsTemplate.setTemplateCode("SMS_252710149").queryOne();
            SMSSender smsSender = (SMSSender) MessageEngine.get(MessageEngineTypeEnum.SMS_SEND).get(null);
            receivePhoneNumbers.stream().distinct().forEach(it -> {
                try {
                    if (!smsSender.smsSend(smsTemplate, it, vars)) {
                        //todo 错误处理
                    }
                } catch (Exception e) {
                    //todo 错误处理
                }
            });
        } catch (Exception e) {
            //todo 错误处理
        }
    }
}
